package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MyClubActivity;
import com.xindaoapp.happypet.activity.Search2Activity;
import com.xindaoapp.happypet.adapter.AttentionAdapter;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.ClubC;
import com.xindaoapp.happypet.bean.LeftMenuBean;
import com.xindaoapp.happypet.bean.LeftMenuBean.Mygrouparray;
import com.xindaoapp.happypet.utils.BitmapHelp;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.MyGridView;

@SuppressLint("ShowToast")
public class LeftMenuFragement_new extends Fragment implements OnClickListener {

    @Override
    public void onResume() {
        super.onResume();
    }


    private LinkedList<ClubC> attention;
    private AttentionAdapter attentionAdapter;

    private Context context;

    // LeftMenu wodeguanzhu
    private RelativeLayout left_menu_guanzhu;
    private MyGridView left_menu_guanzhu_content;
    private ImageView left_menu_guanzhu_image;

    // LeftMenu wangxingern
    private RelativeLayout left_menu_tuijian;
    private MyGridView left_menu_tuijian_content;
    private ImageView left_menu_tuijian_image;


    // LeftMenu ALL

    private RelativeLayout menu_search;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        joinOutReciver = new JoinOutReciver();
        context.registerReceiver(joinOutReciver, new IntentFilter(Constants.JOIN_OUT_GROUP));

        loginSuccessReceiver = new LoginSuccessReceiver();
        context.registerReceiver(loginSuccessReceiver, new IntentFilter(
                Constants.ACTION_LOGIN_STATE_CHANGED));
        return inflater.inflate(R.layout.leftmenu_new, null);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        context = getActivity();
        super.onCreate(savedInstanceState);
    }

    private BitmapUtils bitmapUtils;
    private SharedPreferences sp;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        sp = getActivity().getSharedPreferences("menuconfig", Context.MODE_PRIVATE);
        initLedfMenu();
        initBenDi();
        initAttention();
        fillData();
        // initBitmap();

        // 初始化我的关注集合
        super.onActivityCreated(savedInstanceState);
    }

    private void initBenDi() {
        left_menu_tuijian_content.setAdapter(wxrA);
        wxrA.notifyDataSetChanged();
    }

    private final List<ClubC> top = new ArrayList<ClubC>();
    private final List<ClubC> recommendList = new ArrayList<ClubC>();

    private void initAttention() {
        attention = new LinkedList<ClubC>();
        if (!sp.getString("top", "").equals("")) {
            // ClubCInfo topinfo = JSON.parseObject(sp.getString("top", ""), ClubCInfo.class);
            // top = topinfo.getArray();
            // attention.addAll(top);
        }
        attention.addLast(new ClubC("1000", "添加", "添加", R.drawable.left_menu_add, "111"));
        attentionAdapter = new AttentionAdapter(context, attention);
        left_menu_guanzhu_content.setAdapter(attentionAdapter);
    }

    private void initBitmap() {
        bitmapUtils = BitmapHelp.getBitmapUtils(getActivity());
        bitmapUtils.configDefaultLoadingImage(R.drawable.icon);
        bitmapUtils.configDefaultLoadFailedImage(R.drawable.icon);
        bitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);
    }

    private void initLedfMenu() {
        // 初始化 我的关注
        left_menu_guanzhu = (RelativeLayout) getView().findViewById(R.id.left_menu_guanzhu);
        left_menu_guanzhu_content =
                (MyGridView) getView().findViewById(R.id.left_menu_guanzhu_content);
        left_menu_guanzhu_content.setVisibility(View.VISIBLE);
        left_menu_guanzhu_image = (ImageView) getView().findViewById(R.id.left_menu_guanzhu_image);
        left_menu_guanzhu_image.setImageResource(R.drawable.xiala_ok);
        left_menu_guanzhu.setBackgroundResource(R.color.transparent);
        // left_menu_guanzhu.setOnClickListener(this);

        // 初始化 推荐
        left_menu_tuijian_content =
                (MyGridView) getView().findViewById(R.id.left_menu_tuijian_content);
        // left_menu_tuijian_content.setVisibility(View.GONE);
        left_menu_tuijian = (RelativeLayout) getView().findViewById(R.id.left_menu_tuijian);
        left_menu_tuijian_image = (ImageView) getView().findViewById(R.id.left_menu_tuijian_image);
        // left_menu_tuijian.setOnClickListener(this);


        menu_search = (RelativeLayout) getView().findViewById(R.id.menu_search);
        menu_search.setOnClickListener(this);


        setOnItemClick();
    }

    private void setOnItemClick() {
        final Intent intent = new Intent(context, MyClubActivity.class);
        left_menu_guanzhu_content.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position + 1 == attention.size()) {
                    Intent intent = new Intent(context, AddGroupActivity.class);
                    startActivity(intent);
                } else {
                    intent.putExtra("name", attention.get(position).getName());
                    intent.putExtra("fId", attention.get(position).getFid());
                    startActivity(intent);
                }
            }
        });
        left_menu_guanzhu_content.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                attentionAdapter.notifyDataSetChanged();
                return true;
            }
        });
        left_menu_tuijian_content.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent.putExtra("name", wxrA.getClubs().get(position).getName());
                intent.putExtra("fId", wxrA.getClubs().get(position).getFid());
                startActivity(intent);
            }
        });

        iv_refresh = (ImageView) getView().findViewById(R.id.iv_refresh);


        operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotateanimation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);


        // animation =
        // new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f,
        // Animation.RELATIVE_TO_SELF, 0.5f);
        // animation.setFillAfter(false);
        // animation.setRepeatCount(0);// 设置重复次数
        // animation.setDuration(200);
        // LinearInterpolator lin = new LinearInterpolator();
        // animation.setInterpolator(lin);
        // iv_refresh.setAnimation(animation);
        iv_refresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (operatingAnim != null) {
                    iv_refresh.startAnimation(operatingAnim);
                }
                fillData();
            }
        });
    }

    private float a = 1f;

    public void rotateAnimation() {

        final Bitmap bitmap =
                BitmapFactory.decodeResource(getResources(), R.drawable.select_refursh);
        Bitmap resultBitmap =
                Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        final Canvas canvas = new Canvas(resultBitmap);
        final Matrix matrix = new Matrix();

        new Thread(new Runnable() {
            @Override
            public void run() {
                a += 1f;
                matrix.setRotate(a, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
                canvas.drawBitmap(bitmap, matrix, null);
                iv_refresh.setImageBitmap(bitmap);
            }
        }).start();
    }

    private RotateAnimation animation;

    private final NewAdapter wxrA = new NewAdapter(new ArrayList<ClubC>());
    private JoinOutReciver joinOutReciver;
    private LoginSuccessReceiver loginSuccessReceiver;
    private ImageView iv_refresh;
    private Animation operatingAnim;


    public class NewAdapter extends BaseAdapter {
        private List<ClubC> clubs;

        public NewAdapter(List<ClubC> clubs) {
            super();
            this.clubs = clubs;
        }

        public void addItem(List<ClubC> clubList) {
            this.clubs = clubList;
        }

        public void clearItem() {
            if (clubs != null)
                clubs.clear();
        }


        @Override
        public int getCount() {
            return clubs.size();
        }

        public List<ClubC> getClubs() {
            return clubs;
        }

        @Override
        public Object getItem(int position) {
            return clubs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.left_nemu_list, null);
                holder = new ViewHolder();
                holder.iv_item_list = (CircleImageView) convertView.findViewById(R.id.iv_item_list);
                holder.tv_item_list = (TextView) convertView.findViewById(R.id.tv_item_list);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            // holder.iv_item_list.setImageResource(clubs.get(position).getId());

            ImageLoader.getInstance().displayImage(clubs.get(position).getPicUrl(),
                    holder.iv_item_list);
            holder.tv_item_list.setText(clubs.get(position).getName());
            return convertView;
        }



    }
    private class ViewHolder {
        CircleImageView iv_item_list;
        TextView tv_item_list;
    }

    @SuppressLint("ShowToast")
    public void fillData() {
        RequestParams params = new RequestParams();

        AddClient.get(Address.INDEXMYGROUP, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                if (operatingAnim != null) {
                    iv_refresh.clearAnimation();
                }
                try {
                    LeftMenuBean info = null;
                    try {
                        info = JSON.parseObject(content, LeftMenuBean.class);
                    } catch (Exception e) {
                    }
                    if (null == info) {
                        Toast.makeText(context, R.string.get_error_data, 0).show();
                        return;
                    }
                    if (top.size() > 0) {
                        top.clear();
                    }
                    for (Mygrouparray group : info.mygrouparray) {
                        ClubC clubc = new ClubC(group.fid, group.name, group.type, group.ico, "");
                        top.add(clubc);
                    }
                    if (top.size() > 0) {
                        attentionAdapter.clearItem();
                        top.add(new ClubC("1000", "添加", "添加", R.drawable.left_menu_add, "111"));
                        attentionAdapter.addItem(top);
                        attentionAdapter.notifyDataSetChanged();
                    }

                    if (info.recarray.size() > 0) {
                        recommendList.clear();
                    }
                    for (Mygrouparray group2 : info.recarray) {
                        ClubC clubc =
                                new ClubC(group2.fid, group2.name, group2.type, group2.ico, "");
                        recommendList.add(clubc);
                    }

                    if (recommendList.size() > 0) {
                        // wxrA.clearItem();
                        wxrA.addItem(recommendList);
                        wxrA.notifyDataSetChanged();
                    }

                    info = null;

                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_menu_guanzhu:
                // left_menu_tuijian_content.performClick();

                // left_menu_tuijian_content.setVisibility(View.GONE);

                // left_menu_tuijian_image.setImageResource(R.drawable.xiala_false);

                // left_menu_tuijian.setBackgroundResource(R.color.transparent);

                int visibility = left_menu_guanzhu_content.getVisibility();
                if (visibility == View.GONE) {
                    left_menu_guanzhu.setBackgroundResource(R.color.transparent);
                    left_menu_guanzhu_content.setVisibility(View.VISIBLE);
                    left_menu_guanzhu_image.setImageResource(R.drawable.xiala_ok);
                } else {
                    left_menu_guanzhu.setBackgroundResource(R.color.transparent);
                    left_menu_guanzhu_content.setVisibility(View.GONE);
                    left_menu_guanzhu_image.setImageResource(R.drawable.xiala_false);
                }
                break;
            case R.id.left_menu_tuijian:

                // left_menu_guanzhu_content.performClick();

                // left_menu_guanzhu_content.setVisibility(View.GONE);

                // left_menu_guanzhu_image.setImageResource(R.drawable.xiala_false);

                int visibility2 = left_menu_tuijian_content.getVisibility();
                if (visibility2 == View.GONE) {
                    left_menu_tuijian.setBackgroundResource(R.color.transparent);
                    left_menu_tuijian_content.setVisibility(View.VISIBLE);
                    left_menu_tuijian_image.setImageResource(R.drawable.xiala_ok);
                } else {
                    left_menu_tuijian.setBackgroundResource(R.color.transparent);
                    left_menu_tuijian_content.setVisibility(View.GONE);
                    left_menu_tuijian_image.setImageResource(R.drawable.xiala_false);
                }
                break;
            case R.id.menu_search:
                Intent search = new Intent(context, Search2Activity.class);
                startActivity(search);
                break;
        }
    }


    private class JoinOutReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            fillData();
        }
    }

    private class LoginSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            fillData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (joinOutReciver != null)
            getActivity().unregisterReceiver(joinOutReciver);
        if (loginSuccessReceiver != null)
            getActivity().unregisterReceiver(loginSuccessReceiver);
    }


}
